package part1basiclock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

// 自旋锁
public class TestLock08 {

    // 原子引用线程, 没写参数，引用类型默认为null
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    //上锁
    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "==>mylock");
        // 自旋
        while (!atomicReference.compareAndSet(null, thread)) {
        }
    }

    //解锁
    public void myUnlock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() + "==>myUnlock");
    }

    // 测试
    public static void main(String[] args) {
        TestLock08 spinLockDemo = new TestLock08();
        new Thread(() -> {
            spinLockDemo.myLock();
            System.out.println(Thread.currentThread().getName() + " 执行中...");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.myUnlock();
        }, "T1").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            spinLockDemo.myLock();
            System.out.println(Thread.currentThread().getName() + " 执行中...");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.myUnlock();
        }, "T2").start();
    }

}
